package com.wangyuan.demo.service.impl;

import com.wangyuan.demo.entity.User;
import com.wangyuan.demo.mapper.UserMapper;
import com.wangyuan.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * 用户业务逻辑层接口实现类
 @author Albert
 @date 2025-06-24 15:19:26
 @return
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    @Override
    public void save(User user) {
        // 表单数据校验
        if (!StringUtils.hasLength(user.getUsername().trim())) {
            throw new RuntimeException("用户名不能为空哦");
        }
        if (!StringUtils.hasLength(user.getRealname().trim())) {
            throw new RuntimeException("真实姓名不能为空哦");
        }
        // TODO 密码可以选择不用去除首尾空白字符，因为空格也可以当作密码
        if (!StringUtils.hasLength(user.getPassword())) {
            throw new RuntimeException("密码不能为空哦");
        }
        if (!StringUtils.hasLength(user.getSex().trim())) {
            throw new RuntimeException("性别不能为空哦");
        }
        // 用户名唯一，查询避免重复注册
        User dbUser = userMapper.findByUsername(user.getUsername());
        if (dbUser != null) {
            throw new RuntimeException("该用户已经注册过了哦");
        }
        userMapper.save(user);
    }

    /**
     * 通过用户名和密码查询用户
     *
     * @param username
     * @param password
     * @return User
     */
    @Override
    public User findByUsernameAndPassword(String username, String password) {
        User user = userMapper.findByUsernameAndPassword(username, password);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        return user;
    }

}